package cn.admin.configcenter.configservice.util;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;

public class JSONUtils {

	static ObjectMapper mapper = new ObjectMapper();

	public static String serializeObject(Object o) throws IOException {
		return mapper.writeValueAsString(o);
	}

	public static Object deserializeObject(String s,Class<?> clazz) throws IOException {
		return mapper.readValue(s,clazz);
	}

	public static Object deserializeObject(String s, TypeReference<?> typeReference) throws IOException {
		return mapper.readValue(s,typeReference);
	}

	public static JavaType getCollectionType(Class<?> collectionClass,Class ...elementClasses) {
		return mapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
	}

	public static Object deserializeCollection(String s,JavaType type) throws IOException {
		return mapper.readValue(s,type);
	}

	static {
		mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
	}

}
